import json

import qiniu
from qiniu import BucketManager
import hashlib
import datetime
import os
import math



## 定义七牛
# 七牛图片url
qiniu_url_template = "https://msdn.miaoshouai.com/msdn/image/{}"
access_key = "JDbRmZyb74Z17YhYiUv4sQterC7BRBU7HKH-ptBf"
secret_key = "E1mrlUNOneqOYOn1TvCOSZAdhyGzYvDmR05hFfjD"
bucket_name = "msdn"
qiniu_auth = qiniu.auth.Auth(access_key, secret_key)


def uploadQiniu(fileName, localPath):
    fileName = "msdn/image/" + fileName
    upload_token = qiniu_auth.upload_token("msdn")
    qiniu.put_file(upload_token, fileName, localPath)




def hash_string(string):
    # Create an MD5 object
    md5 = hashlib.md5()

    # Update the object with the string
    md5.update(string.encode())

    # Get the encrypted result
    result = md5.hexdigest()

    # Return the result
    return result


if __name__ == "__main__":
    f = open('图片信息.txt','w')
    # 获取当前文件夹路径
    current_dir = os.getcwd()
    id = 10
    # 遍历当前文件夹的所有文件
    p_list = []
    for file_name in os.listdir(current_dir):
        # 判断是否为文件
        if os.path.isfile(os.path.join(current_dir, file_name)):
            # Check if file_name ends with ".jpg"
            if file_name.endswith(".jpg"):
                # If it does, do something
                # 对字符串进行hash
                productInfo = file_name[:-4].split('_')
                productName = productInfo[0]
                productPrice = math.ceil(int(productInfo[1])/2)
                final_file_name = hash_string(file_name[:-4]) + ".jpg"
                uploadQiniu(final_file_name,file_name)
                print(file_name,qiniu_url_template.format(final_file_name))
                p = {}
                p['id'] = id
                p['img'] = qiniu_url_template.format(final_file_name) + '?imageView2/5/w/216/q/50'
                p['price'] = productPrice
                p['originPrice'] = productPrice + 5
                p['productDescription'] = ''
                p['productName'] = productName + "（1斤）"
                p['tag'] = ''
                p['nodes'] = ''
                p['sortKey'] = 0
                p['displayImg'] = ''
                p['freight'] = 2.5
                p['weight'] = 500
                p['tags'] = []
                p_list.append(p)
                id = id + 1
    f.write(json.dumps(p_list))


    
    f.flush()
    f.close()
                
                
                
